<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;
use think\facade\Event;

class Admin extends Base
{
    protected $name = 'admin';

    protected $type = [
        'last_time' => 'timestamp',
    ];

    protected function role()
    {
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    public function login($param)
    {
        try {
            $v = validate('Common');
            if (!$v->scene('login')->check($param)) {
                return json(['code' => -1, 'msg' => $v->getError()]);
            }
            unset($param['captcha']);
            $param['password'] = md5($param['password']);

            $is = $this->where($param)->find();

            if (empty($is)) {
                return json(['code' => -1, 'msg' => '用户名不存在或密码错误']);
            }
            if ($is['is_del'] == 1 || $is['status'] != 1) {
                return json(['code' => -1, 'msg' => '该用户已被删除或已停用']);
            }
            $is->last_time = time();
            $is->save();
            session('admin_id', $is['id']);
            session('password_token', md5($is->password));
            Logs::adds('管理员【' . $is['admin_name'] . '】登录了系统');

            return json(['code' => 1, 'msg' => '登录成功']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public static function _save($param, $logs): array
    {
        try {

            if (isset($param['id']) && $param['id']) {
                $group = Db::name('auth_group_access')->where('uid', $param['id'])->find();
                if ($param['password']) {
                    $param['password'] = md5($param['password']);
                } else {
                    unset($param['password']);
                }
                $model = parent::update($param);
                if ($group['group_id'] != $param['role_id']) {
                    Db::name('auth_group_access')->where('uid', $param['id'])->update(['group_id' => $param['role_id']]);
                }
                $model->operation = 'save';
            } else {
                if (parent::where('admin_name', $param['admin_name'])->count()) {
                    return ['code' => -1, 'msg' => '用户名已被添加'];
                }
                $model = parent::create($param);
                $model->operation = 'create';
                Db::name('auth_group_access')->insert(['uid' => $model->id, 'group_id' => $model->role_id]);
                Logs::adds('后台添加新管理员，账号【' . $model->admin_name . '】');
            }

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
